<?php
declare (strict_types=1);

namespace app\common\listener;

use app\common\facade\Jpush;
use app\common\model\OrderProduct;
use app\common\model\Product;
use app\common\model\UserNotify;
use app\common\model\UserProductDiscount;

class GiveProductDiscount
{
    public function handle($id)
    {
        try {
            $list = OrderProduct::where('order_id', $id)
                ->with(['productField', 'user'])
                ->field('id,order_id,uid,pid,num')->select();
            $discount = [];
            foreach ($list as $item) {
                if ($item->productField->give_discount_amount > 0 &&
                    $item->productField->give_discount_pid &&
                    $item->productField->give_discount_day > 0) {

                    $product_title = Product::where('id', $item->productField->give_discount_pid)->value('title');
                    $discount[] = [
                        'uid'         => $item->uid,
                        'pid'         => $item->productField->give_discount_pid,
                        'amount'      => $item->productField->give_discount_amount,
                        'create_time' => time(),
                        'expire_time' => time() + $item->productField->give_discount_day * 86400,
                        'order_id'    => $item->order_id,
                        'sn'          => date('YmdHis') . $item->id . strtolower(generateCode(6)),
                        'explain'     => '仅限【'.$product_title.'】使用',
                        'num'         => $item->num
                    ];

                    $content = "你有一张新的抵扣券到账，限【'.$product_title.'】，快去使用吧！";
                    $parameter = ['event_type'=>1005,'sub_event_type'=>1100];
                    $extra = ['extras'=>['parameter'=>json_encode($parameter)]];

                    Jpush::sendSingleNotify($item->user->registration_id, $content, $extra, $item->uid);

                    UserNotify::create([
                        'uid' => $item->uid,
                        'type' => 8,
                        'title' => '抵扣券到账',
                        'content' => $content
                    ]);
                }
            }
            if (!empty($discount)) {
                (new UserProductDiscount())->insertAll($discount);
            }
            return $discount;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), -1);
        }
    }


}